/**
 * @Date 2023-02-21 17:44:34
 * @Remark
 */

// lib
import axios, { AxiosError, AxiosResponse } from "axios";
// config
import { HTTP_SETTING } from "config/setting";
// script & methods & public
import logUtils from "utils/logUtils";
import timeUtils from "utils/timeUtils";
import toast from "components/toast";
// state
// http
import { createApiUrl } from "public/http/core";
import { bag } from "public/http/api";
// service
// api
import { API_FILE_UPLOAD, ResFileUpload } from "./api";
// interface
import { ERROR_CODE_MAP } from "public/http/model";
import { RcFile } from "antd/lib/upload";
import { getToken } from "project/token";
// 其它

// 上传地址
export function getUploadFileUrlService() {
  const path = createApiUrl(API_FILE_UPLOAD);
  return path;
}

/**
 * 自定义上传
 * https://www.cnblogs.com/cjh1111/p/7017295.html
 */
export async function uploadFileService(
  file: RcFile | Blob | undefined,
  fileName: string,
  onUploadProgress?: (progressEvent: any) => void,
) {
  logUtils.info("上传文件", file);
  const url = getUploadFileUrlService();
  // 创建form对象
  const param: FormData = new FormData();
  // 创建返回
  const data: BagData<UploadFileData> = bag([]);
  if (!file) {
    data.fail.push({
      result: 998,
      message: ERROR_CODE_MAP[998],
    });
    return data;
  }
  // 通过append向form对象添加数据,默认文件名file
  param.append("file", file, fileName);

  const newInstance = axios.create({
    timeout: HTTP_SETTING.TIMEOUT_LONG,
    onUploadProgress: (progressEvent) => {
      if (onUploadProgress) {
        onUploadProgress(progressEvent);
      }
    },
  });
  // 请求实例
  return newInstance
    .post(getUploadFileUrlService(), param, {
      headers: {
        // 添加请求头,表单格式
        "Content-Type": "multipart/form-data",
        authorization: getToken(),
      },
    })
    .then((res: AxiosResponse<ResFileUpload>) => {
      // 打印结果
      logUtils.info(`method: UPLOAD || url: ${url}`, "res");
      logUtils.log(res.data);
      data.payload = {
        name: fileName,
        uploadTime: timeUtils.format(new Date(), 1),
        url: res.data.data[0].uri || "",
      };
      return data;
    })
    .catch((error: AxiosError) => {
      const res: AxiosResponse<unknown, any> | undefined = error.response;
      logUtils.info(`method: UPLOAD || url: ${url}`, "res");
      if (!res) {
        const result: Res = {
          result: 999,
          message: ERROR_CODE_MAP[999],
        };
        data.err.push(result);
      } else {
        logUtils.log(res.data);
        const result: Res = {
          result: res.status,
          message: ERROR_CODE_MAP[res.status],
        };
        data.err.push(result);
      }
      return data;
    });
}

// 不再使用这个富文本编辑器
export async function braftEditorUploadService(data: any) {
  const result = await uploadFileService(
    data.file,
    data.file.name,
    (event: any) => {
      data.progress((event.loaded / event.total) * 100);
    },
  );
  if (result.payload) {
    data.success({
      url: result.payload.url,
      meta: {
        id: result.payload.url,
        alt: result.payload.url,
      },
    });
  }
  toast.whenFailOrErr(result);
}
